/**
 * Created by kule on 2017/7/3.
 */
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';

export const flatObjRaw=function(data,key='',doLoop,result={}){
    let item;
    let deepKey;
    let preKey;
    let isEmpty=true;
    for(let k in data){
        isEmpty=false;
        item=data[k];
        preKey=key||k;
        deepKey=key?`${key}.${k}`:k;
        if(doLoop(k,item,preKey,deepKey,result)){
        }else{
            result[deepKey]=item;
        }
    }
    if(isEmpty){
        result[key]=data;
    }
    return result;
};
export const flatObj=function(data,key='',result={}){
    const doLoop=(key,item,preKey,deepKey,result)=>{
        if(typeof item==='object'){
            flatObj(item,deepKey,result);
            return true;
        }
        return false;
    };
    return flatObjRaw(data,key,doLoop,result);
};
const regEnd=/\.\$end$/;
export const flatObjWithEnd=function(data,key='',result={}){
    const doLoop=(key,item,preKey,deepKey,result)=>{
        if(regEnd.test(key)){
            result[deepKey.replace(regEnd,'')]=item;
            return true;
        }
        if(typeof item==='object'){
            flatObj(item,deepKey,result);
            return true;
        }
        return false;
    };
    return flatObjRaw(data,key,doLoop,result);
};
export const flatObjSafe=function(data,key,result){
    const doLoop=(key,item,preKey,deepKey,result)=>{
        if(isArray(item)||isPlainObject(item)){
            flatObjSafe(item,deepKey,result);
            return true;
        }
        return false;
    };
    return flatObjRaw(data,key,doLoop,result)
};
export const flatObjAndIgnoreArray=function(data,key='',result={}){
    const doLoop=(key,item,preKey,deepKey,result)=>{
        if(isPlainObject(item)){
            flatObjAndIgnoreArray(item,deepKey,result);
            return true;
        }
        return false;
    };
    return flatObjRaw(data,key,doLoop,result);
};